package com.yxjx.duoxue.my;

import java.io.IOException;

import org.apache.http.ParseException;
import org.json.JSONException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.PageLoading;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.dao.Dao;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.URMobileCheckResponse;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.payment.ClientUserKidsDTS;
import com.yxjx.duoxue.payment.KidInfoEditActivity;
import com.yxjx.duoxue.payment.datamodel.DMKidInfoRefObject;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class UserLoginActivity extends BaseActionBarActivity {
	
	private EditText mPhoneNum;
	private EditText mPassword;
	private Context mContext;
	
	public static final int REQ_CODE_REG_FOR_LOGIN = 1;
	public static final int REQ_CODE_FIRST_USER_EDIT_FOR_FINISH = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_user_login);
		customizeActionBarTitle("登录");
		
		mContext = this;
		
		mPhoneNum = (EditText) findViewById(R.id.phone_num);
		mPassword = (EditText) findViewById(R.id.password);
		
		mPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				hideIME(mPassword);
				//不同的手机平台 EditText xml设置的actionId可能不生效。
				mClickListener.onClick(findViewById(R.id.root).findViewById(R.id.login_button));
				return false;
			}
		});
		
		int[] ids = new int[] {
				R.id.login_button,
				R.id.forget_password,
				R.id.free_reg,
				R.id.scroll_internal
		};
		
		for (int id : ids) {
			UIHelper.setClickListener(findViewById(R.id.root), id, mClickListener);
		}
		
		// auto fill some field. 自动填入手机号
		mPhoneNum.setText(UserLoginResponse.getPhoneNum(getApplicationContext()));
		
		StatHelper.addKVEvent(mContext, "event_my_login_page");
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQ_CODE_REG_FOR_LOGIN:
			if (resultCode == RESULT_OK) {
				mPhoneNum.setText(Utils.getValueFromSharedPreference(getApplicationContext(), Yx.KEY_PHONE_NUM));
				mPassword.setText(Utils.getValueFromSharedPreference(getApplicationContext(), Yx.KEY_PHONE_PASSWORD));
				//  注册登录成功时去做完善学生信息的动作。
				int userReg = data.getIntExtra(Yx.KEY_REG_TYPE, -1);
				login(mPhoneNum, (userReg == Yx.REG_TYPE_NEW_USER));
			}
			break;
			
		case REQ_CODE_FIRST_USER_EDIT_FOR_FINISH:
			finish();
			break;
		default:
			break;
		}
	}
	
	private void login(final View arg0, final boolean firstUserReg) {
		UIHelper.hideIME(arg0);
		final String phoneNum = mPhoneNum.getText().toString();
		final String pwd = mPassword.getText().toString();
		// 检查手机格式和密码格式
		if (!Utils.isMobileNumber(phoneNum)) {
			UIHelper.showTips(arg0, "手机号码格式错误");
			return;
		}
		
		dialog = MyProgressDialog.show(this, "", "正在登录");
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					URMobileCheckResponse rsp;
					rsp = UserReg.salt(phoneNum);
					UserLoginResponse ret = UserReg.userLogin(arg0.getContext(), rsp, phoneNum, pwd);
					if (ret.isOk()) {
						UIHelper.showTips(arg0, "登录成功");
						Dao.setUlRsp(mContext, ret);
						
						setResult(RESULT_OK, getIntent());
						
						StatHelper.addKVEvent(mContext, "event_my_login_success");
						
						// 尝试获取新消息
						PageLoading.queryNewMessages(getApplicationContext());
						
						
						if (firstUserReg) {
							Intent intent = new Intent(UserLoginActivity.this, KidInfoEditActivity.class);
							ClientUserKidsDTS extra = Dao.getUserKidInfo(getApplicationContext());
							intent.putExtra(KidInfoEditActivity.KEY_SHOW_SKIP_BTN, true);
							intent.putExtra(KidInfoEditActivity.KEY_KID_INFO_TOTAL, DMKidInfoRefObject.from(UserLoginActivity.this, extra));
							startActivityForResult(intent, REQ_CODE_FIRST_USER_EDIT_FOR_FINISH);
						} else {
							finish();
						}
						
					} else if (rsp.getCode() == MsgCode.USER_NOT_EXISTS) {
						UIHelper.showTips(arg0, "用户不存在，自动跳转到注册页面");
						jumpToUserRegActivity(phoneNum, pwd, Yx.REG_TYPE_NEW_USER);
					} else {
						UIHelper.showTips(arg0, "登录失败," + MsgCode.descFor(ret));
					}

				} catch (ParseException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
					UIHelper.showTips(arg0, "登录失败，网络错误");
				} finally {
					tryDismissDialog();
				}
				
			}
		});
		thread.start();
	}

	protected void jumpToUserRegActivity(String phoneNum, String pwd, int regType) {
		Intent intent = new Intent(getApplicationContext(), UserRegActivity.class);
		intent.putExtra(Yx.KEY_REG_TYPE, regType);
		intent.putExtra(Yx.EXTRA_USER_PASSWORD, pwd);
		intent.putExtra(Yx.EXTRA_USER_PHONE_NUM, phoneNum);
		startActivityForResult(intent, REQ_CODE_REG_FOR_LOGIN);
	}

	public void tryDismissDialog() {
		if (dialog != null) {
			dialog.dismiss();
			dialog = null;
		}
	}

	private View.OnClickListener mClickListener = new OnClickListener() {
		
		@Override
		public void onClick(final View arg0) {
			String phoneNum = mPhoneNum.getText().toString();
			String pwd = mPassword.getText().toString();
			
			switch (arg0.getId()) {
			case R.id.scroll_internal:
				hideIME(arg0);
				break;
			case R.id.free_reg:
				jumpToUserRegActivity(phoneNum, "", Yx.REG_TYPE_NEW_USER);
				break;
			case R.id.forget_password:
				StatHelper.addKVEvent(mContext, "event_my_fetch_click");
				jumpToUserRegActivity(phoneNum, "", Yx.REG_TYPE_GET_PWD);
				break;
			case R.id.login_button:
				login(arg0, false);
				break;
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
		}
	};
	private ProgressDialog dialog;

}
